#include "filewatcher.h"
#include <QDebug>

FileWatcher::FileWatcher(QObject *parent)
    : QObject(parent)
    , m_watcher(new QFileSystemWatcher(this))
{
    connect(m_watcher, &QFileSystemWatcher::fileChanged, this, &FileWatcher::onFileChanged);
}

QString FileWatcher::filePath() const
{
    return m_filePath;
}

void FileWatcher::setFilePath(const QString &newFilePath)
{
    if (m_filePath == newFilePath)
        return;

    if (!m_watcher->files().isEmpty())
        m_watcher->removePaths(m_watcher->files());

    m_filePath = newFilePath;
    emit filePathChanged();
}

void FileWatcher::startWatching()
{
    if (m_filePath.isEmpty()) {
        qWarning() << "FileWatcher: No file path set";
        return;
    }

    if (m_filePath.isEmpty()) {
        qWarning() << "FileWatcher: Invalid file path" << m_filePath;
        return;
    }

    if (!m_watcher->files().contains(m_filePath)) {
        m_watcher->addPath(m_filePath);
        qDebug() << "FileWatcher: Started watching" << m_filePath;
    }
}

void FileWatcher::stopWatching()
{
    if (!m_watcher->files().isEmpty()) {
        m_watcher->removePaths(m_watcher->files());
        qDebug() << "FileWatcher: Stopped watching files";
    }
}

bool FileWatcher::enabled()
{
    return m_enabled;
}

void FileWatcher::setEnabled(bool enabled)
{
    if (m_enabled == enabled) {
        return;
    }

    if (enabled) 
        startWatching();
    else
        stopWatching();

    
    m_enabled = enabled;
}

void FileWatcher::onFileChanged(const QString &path)
{
    qDebug() << "FileWatcher: File changed:" << path;
    emit fileChanged(path);

    // 重新添加监视，因为某些系统在文件被修改后会移除监视
    if (!m_watcher->files().contains(path)) {
        m_watcher->addPath(path);
    }
}
